package com.zf.nospring.rabbitmq.alternate_exchange;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.zf.nospring.rabbitmq.utils.RabbitUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;

/**
 * 备份交换机；
 * <p>
 * 当发送的某个交换机的消息无法被路由时（无法找到队列），如果交换机设置了备份交换机，那么就会把无法路由的消息发送到备份交换机。否则丢弃消息
 * <p>
 * 为一个交换机声明 备份交换机，使用 "alternate-exchange"="备份交换机名称" 参数，
 * 备份交换机一般声明为 fanout类型，确保消息能够进入备份交换机绑定的队列中
 */
public class AlternateProducer {
    public static final String testAlterNormalExchange = "test_alter_normal_exchange";
    public static final String testAlternateExchange = "test_alter_alternate_exchange";
    public static final String testAlterNormalQueue = "test_alter_normal_queue";
    public static final String testAlternateQueue = "test_alter_alternate_queue";
    public static final String testAlterNormalRouteKey = "test_alter_normal_route_key";

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitUtils.getDefaultConnection();
        Channel channel = connection.createChannel();

        // 声明备份交换机和队列
        channel.exchangeDeclare(testAlternateExchange, BuiltinExchangeType.FANOUT, true, false, null);
        channel.queueDeclare(testAlternateQueue, true, false, false, null);
        channel.queueBind(testAlternateQueue, testAlternateExchange, "");

        // 声明正常交换机和队列
        channel.queueDeclare(testAlterNormalQueue, true, false, false, null);
        // 指定备份交换机
        HashMap<String, Object> exArgs = new HashMap<>();
        exArgs.put("alternate-exchange", testAlternateExchange);
        channel.exchangeDeclare(testAlterNormalExchange, BuiltinExchangeType.DIRECT, true, false, exArgs);
        channel.queueBind(testAlterNormalQueue, testAlterNormalExchange, testAlterNormalRouteKey);

        // 发送无法路由的消息
        for (int i = 1; i <= 2; i++) {
            String msg = "无法路由消息" + i;
            channel.basicPublish(testAlterNormalExchange, testAlterNormalRouteKey + i, null, msg.getBytes(StandardCharsets.UTF_8));
        }
        // 发送正常路由的消息
        for (int i = 1; i <= 2; i++) {
            String msg = "正常路由消息" + i;
            channel.basicPublish(testAlterNormalExchange, testAlterNormalRouteKey, null, msg.getBytes(StandardCharsets.UTF_8));
        }

        channel.close();
        connection.close();
    }
}
